<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of Gamegiftbag_Controlers
 *
 * @author Samuel
 */
defined ( 'BASEPATH' ) or die ( 'forbidden' );
class Gamegiftbag_Controller extends Controller {
	private $inc;
	private $activityTypeList; // 活动类型对应表
	private $dynactivityTypeList; //活动礼包类型表
	private $objectTypeList; // 物品类型表
	function _init() {
		check_level ( 50, segment ( 0 ), segment ( 1 ), segment ( 2, 'index' ) );
		
		$this->inc = $this->config ['inc'];
		
		// 得到选择的区号
		$areanum = $_SESSION ['area_selected_id'];
		if ($areanum == '') {
			echo "<script>alert('" . translate ( 'C_SELECT_AREA_TEXT' ) . "');</script>";
			return;
		}
		
		// 活动对应表在dynamic_activity_map中
		$sql = "SELECT *  FROM dynamic_activity_map ";
		$this->db->query ( $sql );
		while ( $n = $this->db->get_array ( 'default' ) ) {
			 //print_r($n);
			 //exit();
			if ($n['activityid'] < 1000)
			{
				$this->activityTypeList [$n ['activityid']] ['activityid'] = $n ['activityid'];
				$this->activityTypeList [$n ['activityid']] ['activityname'] = $n ['activityname'];
				$this->activityTypeList [$n ['activityid']] ['activitytable'] = $n ['activitytable'];
				$this->activityTypeList [$n ['activityid']] ['displayview'] = $n ['displayview'];
				$this->activityTypeList [$n ['activityid']] ['messageid'] = $n ['messageid'];
			}
		}
		//print_r($this->activityTypeList);
		//exit(0);
		$tmp_connect = $this->load->database('center_db') or die("load failed!".mysql_error());
		$tmpsql = "SELECT id, name FROM dynamic_type_object ";
		$tmp_connect->query($tmpsql) or die("query failed!".mysql_error());
		while($dynrow = $tmp_connect->get_array()){
			$this->dynactivityTypeList[$dynrow['id']] = $dynrow['name'];
		}
		// 把type表读到内存中来
		$type_connect = $this->load->database ( 'type_db' );
		$sql = "SELECT id, name FROM type_object ";
		$type_connect->query ( $sql );
		while ( $row = $type_connect->get_array () ) {
			// 几个特殊的标识需要转换下
			$this->objectTypeList [$row ['id']] = $row ['name'];
		}
		// 把角色列表传过去
		$this->view->assign ( 'professionlist', $this->inc ['type_proffessionid'] );
	}
	function index() {
		$area_host = ! empty ( $_SESSION ['area_selected_host'] ) ? $_SESSION ['area_selected_host'] : '';
		if ($area_host == '') {
			echo "<script>alert('" . translate ( 'C_SELECT_AREA_TEXT' ) . "');</script>";
		}
		$this->view->display ( "activity/gamegiftbag/index" );
	}
	function flexigrid() {
		list ( $colkey, $colsinfo, $where, $sortname, $sortorder, $offset, $rp, $page ) = $this->common->get_flexigrid_params ();
		
		$area_host = ! empty ( $_SESSION ['area_selected_host'] ) ? $_SESSION ['area_selected_host'] : '';
		$url = $area_host . "action=10";
		// echo "url = $url ";
		// print_r($url);
		// exit(0);
		$strResult = vpost ( $url );
		
		$row = json_decode ( $strResult, true );
		
		// 因服务器传过来的数据有重复的。在此，需要去重了
		 //print_r($row);
		 //exit(0);
		$newRow = array ();
		foreach ( $row as $key => $value ) {
			// 只有运营活动才显示 出来
			if ($value['activityId'] < 1000 && (1 == $value ['activity_type'] || 3 == $value ['activity_type'])
					&& ($value['activityId'] != 250 && $value['activityId'] != 251 && $value['activityId'] != 406)) { // 0为运营活动，1是限时活动
				$newRow [$value ['activityId']] = $value;
			}
		}
		// print_r($newRow);
		// exit(0);
		$rows = array ();
		foreach ( $newRow as $key => $value ) {
			$value ['activity_type'] = $this->inc ['activity_type'] [$value ['activity_type']];
			$rows [] = array (
					'id' => $key,
					'cell' => $value 
			);
		}
		// var_dump($rows);
		// exit();
		$total = count ( $rows );
		$result = array (
				'page' => $page,
				'total' => $total,
				'rows' => $rows 
		);
		
		echo json_encode ( $result );
	}
	
	// 此函数在此界面 没有用到
	function add() {
		set_time_limit ( 30 );
		if (is_submit ()) {
			$rowdata = $_POST ['row'];
			$area_host = $rowdata ['area_host'];
			unset ( $rowdata ['area_host'] );
			$rowdata ["start_time"] = strtotime ( $rowdata ["start_time"] );
			$rowdata ["end_time"] = strtotime ( $rowdata ["end_time"] );
			$str = array_to_stringparam ( $rowdata );
			$str = $area_host . $str . "action=35";
			$strResult = vpost ( $str );
			
			$result = 0;
			// 操作失败或者连接失败
			if ($strResult != '0' || $strResult === FALSE) {
				$result = 1;
			} else {
				insert_log ( translate ( 'MENU_ACTIVITY_ACTIVITYEDIT' ), translate ( 'ADD' ), NULL, array (
						"name" => $area_host . 'activity_id:' . $rowdata ['activity_id'] 
				) );
			}
			cp_tips ( $result == 0 ? "success" : "error" );
		}
		$this->view->assign ( 'area_host', $this->form->select ( 'row[area_host]', get_area_list_host (), '', array (
				'id' => 'area_host' 
		) ) );
		// $this->view->assign('activity_isever',$this->form->select('row[activity_isever]',$this->inc['activity_isever'],'',array('id'=>'activity_isever')));
		$this->view->display ( "activity/activitytime/add" );
	}
	function edit($id = 0) {
		$areanum = $_SESSION ['area_selected_id']; // 得到区号
		                                           // echo " areanum:$areanum id = $id ";
		                                           // $dbLink = $this->getAreaConn();
		$areanum = $_SESSION ['area_selected_id'];
		$dblink = getTmpDbConnect ( PLATFORM_ALL, 'all', $areanum, DBTYPE_DYNAMIC );
		// echo " dblink = $dbLink ";
		if (is_submit ()) {
			$rowdata = $_POST ['row'];
			// print_r($rowdata);
			// exit(0);
			// 分情况 来处理了。。
			$result = $this->editGift ( $id, $rowdata, $dblink );
			
			if (true == $result) {
				// action都是51
				$area_host = ! empty ( $_SESSION ['area_selected_host'] ) ? $_SESSION ['area_selected_host'] : '';
				$url = $area_host . "action=51&messageid=" . $this->activityTypeList [$id] ['messageid'];
				// echo " url = $url ";
				// exit(0);
				$ret = vpost ( $url, 10 );
				// 服务器返回，表示成功
				cp_tips ( 0 == $ret ? "success" : "error" );
				insert_log ( translate ( 'MENU_ACTIVITY_ACTIVITYEDIT' ), translate ( 'EDIT' ), NULL, array (
				"name" => $area_host . 'activity_id:' . $rowdata ['activity_id']));
			} else {
				cp_tips ( "error" );
			}
		}
		/*
		 * $area_host = !empty($_SESSION['area_selected_host']) ? $_SESSION['area_selected_host'] : '';
		 * $strResult = vpost($area_host . "action=10&id={$id}");
		 * $row = json_decode($strResult, true);
		 */
		// 先在对应表中查下，是否有这样的一个礼包号。。。
		if (! array_key_exists ( $id, $this->activityTypeList )) {
			echo " gift id not exists giftID:$id ";
			return;
		}
		
		// 通过区号找到相应数据库的连接
		
		// 查找到相应的数据
		switch ($id) {
			case 1003 :
				$sql = "select * from " . $this->activityTypeList [$id] [activitytable] . " where type = 0";
				break;
			case 1004 :
				$sql = "select * from " . $this->activityTypeList [$id] [activitytable] . " where type = 1";
				break;
			default :
				$sql = "select * from " . $this->activityTypeList [$id] [activitytable];
				break;
		}
		// $sql = "select * from " . $this->activityTypeList [$id] ['activitytable'];
		// echo " sql:$sql ";
		
		$dblink->query ( $sql ) or die("query failed!" . mysql_error());
		while ( $n = $dblink->get_array ( 'default' ) ) {
			// 如果有类型表，在此需要把中文名字也显示出来
			if (array_key_exists ( "giftbag_id", $n )) {
				$n ['giftbag_id'] = $n ['giftbag_id'] . "(" . $this->dynactivityTypeList[$n ['giftbag_id']] . ")";
			}
			$rows [$n ['id']] = $n;
			if (array_key_exists("objectid", $n)){
				$n['objectid'] = $n['objectid'] . "(" . $this->objectTypeList[$n['objectid']] . ")";
				$dynrows[$n['id']] = $n;
			}
		}
		// print_r($rows);
		// exit(0);
		// 转成编号来索引
		$rows = array_values ( $rows );
		$dynrows = array_values($dynrows);
		$dblink->free ();
		$this->view->assign ( "row", $rows );
		$this->view->assign("dynrow", $dynrows);

		// echo " id = $id";
		//print_r($this->activityTypeList);
		//exit(0);
		$this->view->display ( "activity/activityedit/" . $this->activityTypeList [$id] ['displayview'] );
	}
	
	// 得到区数据库的连接
	/*
	 * function getAreaConn() {
	 * $areanum = $_SESSION['area_selected_id'];
	 *
	 * //因需要修改数据，在此需要 连主数据库 即zucong = 1
	 * $sql = "SELECT * FROM server_mapping WHERE delete_flag=0 and zucong = 1 and area_num = $areanum";
	 * $one = $this->db->one($sql);
	 *
	 * if (NULL == $one) {
	 * echo " can not get database info sql:$sql";
	 * cp_tips("error");
	 * }
	 * //print_r($one);
	 * //新创建一个连接
	 * $areaSqlConfig = array
	 * (
	 * 'library' => 'database',
	 * 'type' => 'mysql',
	 * 'host' => $one['databaseip'],
	 * 'name' => $one['dynname'],
	 * 'user' => $one['username'],
	 * 'password' => $one['password'],
	 * );
	 * //print_r($areaSqlConfig);
	 * $link = new Database($areaSqlConfig);
	 * //$link->select_db('taitan_dyn_yf');
	 * return $link;
	 * }
	 */
	// 传入礼包编号及相关的数据
	function editGift($activityid, $data, $dblink) {
		$result = true;
		// print_r($data);
		$tablename = $this->activityTypeList [$activityid] ['activitytable'];
		
		// echo "activityid:".$activityid." tablename:$tablename ";
		// print_r($data);
		// exit(0);
		// 先清下数据库中的数据
		switch ($activityid) {
			case 1003 :
				$sql = "delete from $tablename " . "where type = 0";
				break;
			case 1004 :
				$sql = "delete from $tablename " . "where type = 1";
				break;
			default :
				$sql = "delete from $tablename ";
				break;
		}
		// $sql = "delete from $tablename ";
		// echo " sql:$sql ";
		if (true != $dblink->query ( $sql )) {
			echo " delete data error sql:$sql";
			cp_tips ( "error" );
		}
		
		switch ($activityid) {
			case 201 : // 冲级礼包
				for($i = 0; $i < count ( $data ['giftbag_name'] ); ++ $i) {
					// echo " giftbagid:".$data['giftbag_id'][$i];
					// 有数据，才进行插入数据操作
					if (! empty ( $data ['giftbag_id'] [$i] ) && ! empty ( $data ['giftbag_name'] [$i] )) {
						// 提取objectid出来
						$len = stripos ( $data ['giftbag_id'] [$i], '(' ) == 0 ? 10 : stripos ( $data ['giftbag_id'] [$i], '(' );
						$data ['giftbag_id'] [$i] = substr ( $data ['giftbag_id'] [$i], 0, $len );
						$sql = "insert $tablename(level,giftbag_id,giftbag_name) values(" . $data ['level'] [$i] . ",'" . $data ['giftbag_id'] [$i] . "','" . $data ['giftbag_name'] [$i] . "')";
						if (true != $dblink->query ( $sql )) {
							echo " insert data error sql:$sql";
							cp_tips ( "error" );
						}
					}
				}
				break;
			case 204 : // vip礼包
			           // 把收到 的数据一个个的插入
			           // foreach ($data[''] as $key => $value)
				for($i = 0; $i < count ( $data ['giftbag_name'] ); ++ $i) {
					// echo " giftbagid:".$data['giftbag_id'][$i];
					// echo " giftbagname:".$data['giftbag_name'][$i];
					// 有数据，才进行插入数据操作
					if (! empty ( $data ['giftbag_id'] [$i] ) && ! empty ( $data ['giftbag_name'] [$i] )) {
						// 提取objectid出来
						$len = stripos ( $data ['giftbag_id'] [$i], '(' ) == 0 ? 10 : stripos ( $data ['giftbag_id'] [$i], '(' );
						$data ['giftbag_id'] [$i] = substr ( $data ['giftbag_id'] [$i], 0, $len );
						$sql = "insert $tablename(viplevel,giftbag_id,giftbag_name) values(" . $data ['viplevel'] [$i] . ",'" . $data ['giftbag_id'] [$i] . "','" . $data ['giftbag_name'] [$i] . "')";
						
						if (true != $dblink->query ( $sql )) {
							echo " insert data error sql:$sql";
							cp_tips ( "error" );
						}
					}
				}
				break;
			case 402 : // 七天惊喜（现在是累计登录）
			           // 把收到 的数据一个个的插入
			           // foreach ($data[''] as $key => $value)
				for($i = 0; $i < count ( $data ['giftbag_id'] ); ++ $i) {
					// echo " giftbagid:".$data['giftbag_id'][$i];
					// 有数据，才进行插入数据操作
					if (! empty ( $data ['giftbag_id'] [$i] )) {
						// 提取objectid出来
						$len = stripos ( $data ['giftbag_id'] [$i], '(' ) == 0 ? 10 : stripos ( $data ['giftbag_id'] [$i], '(' );
						$data ['giftbag_id'] [$i] = substr ( $data ['giftbag_id'] [$i], 0, $len );
						
						$sql = "insert $tablename(day,profession,giftbag_count,giftbag_id) values(" . $data ['day'] [$i] . "," . -1 . "," . 1 . "," . $data ['giftbag_id'] [$i] . ")";
						
						if (true != $dblink->query ( $sql )) {
							echo " insert data error sql:$sql";
							cp_tips ( "error" );
						}
					}
				}
				break;
			case 301 :
				for($i = 0; $i < count ( $data ['giftbag_name'] ); ++ $i) {
					// echo " giftbagid:".$data['giftbag_id'][$i];
					// 有数据，才进行插入数据操作
					if (! empty ( $data ['giftbag_id'] [$i] ) && ! empty ( $data ['giftbag_name'] [$i] )) {
						// 提取objectid出来
						$len = stripos ( $data ['giftbag_id'] [$i], '(' ) == 0 ? 10 : stripos ( $data ['giftbag_id'] [$i], '(' );
						$data ['giftbag_id'] [$i] = substr ( $data ['giftbag_id'] [$i], 0, $len );
						$sql = "insert $tablename(time,giftbag_id,giftbag_name) values(" . $data ['time'] [$i] . ",'" . $data ['giftbag_id'] [$i] . "','" . $data ['giftbag_name'] [$i] . "')";
						
						if (true != $dblink->query ( $sql )) {
							echo " insert data error sql:$sql";
							cp_tips ( "error" );
						}
					}
				}
				break;
			case 206 :
				for($i = 0; $i < count ( $data ['giftbag_name'] ); ++ $i) {
					// echo " giftbagid:".$data['giftbag_id'][$i];
					// 有数据，才进行插入数据操作
					if (! empty ( $data ['giftbag_id'] [$i] ) && ! empty ( $data ['giftbag_name'] [$i] )) {
						// 提取objectid出来
						$len = stripos ( $data ['giftbag_id'] [$i], '(' ) == 0 ? 10 : stripos ( $data ['giftbag_id'] [$i], '(' );
						$data ['giftbag_id'] [$i] = substr ( $data ['giftbag_id'] [$i], 0, $len );
						$sql = "insert $tablename(day,giftbag_id,giftbag_name) values(" . $data ['day'] [$i] . ",'" . $data ['giftbag_id'] [$i] . "','" . $data ['giftbag_name'] [$i] . "')";
						
						if (true != $dblink->query ( $sql )) {
							echo " insert data error sql:$sql";
							cp_tips ( "error" );
						}
					}
				}
				break;
			default :
				echo " error activityid:$activityid ";
				break;
		}
		
		return $result;
	}
}

?>
